package br.com.puertorico.model.template;

import java.util.Properties;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.apache.velocity.runtime.resource.util.StringResourceRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StringVelocityTemplateDocumentoBuilder extends
		AbstractTemplateDocumentoBuilder {

	private static final Logger LOG = LoggerFactory
			.getLogger(StringVelocityTemplateDocumentoBuilder.class);

	private static VelocityEngine engine;

	/**
	 * Prepara o processador de um template em particular (localizado dentro do
	 * contexto da aplica&ccedil;&atilde;o)
	 *
	 * @param arquivoTemplate
	 *            Nome do template desejado
	 */
	public StringVelocityTemplateDocumentoBuilder(String name, byte[] bytes) {
		try {
			Properties props = new Properties();
			props.load(this
					.getClass()
					.getClassLoader()
					.getResourceAsStream(
							"StringTemplateDocumentoBuilder.properties"));
			if (engine == null) {
				engine = new VelocityEngine(props);
				engine.init();
			}
			StringResourceRepository repo = StringResourceLoader
					.getRepository();
			// TODO[daniel.camargo]: melhorar cache
			repo.putStringResource(name, new String(bytes));
			template = engine.getTemplate(name);
		} catch (ResourceNotFoundException e) {
			LOG.error("Nao foi possivel carregar o template desejado.", e);
			throw new RuntimeException(e);
		} catch (ParseErrorException e) {
			LOG.error("Erro ao processar arquivo de template.", e);
			throw new RuntimeException(e);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}